# -*- coding: utf-8 -*-
import datetime
import math
import scrapy
import re
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item, urllib, time, urljoin, json, urlencode
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class ZhejiangNingboPolicy(BaseTaxPolicySpider):
    name = 'zhejiang_ningbo_nh_policy'

    province = '浙江省'
    city = '宁波市'
    # county = ''
    park = ''
    page_size = 18 * 2

    def __init__(self, get_next=False, **kwargs):
        super().__init__(**kwargs)
        print(get_next)
        self.get_next = get_next

    @classmethod
    def update_settings(cls, settings) -> None:
        downloader_middlewares = settings.getdict("DOWNLOADER_MIDDLEWARES")
        new_settings = {
            **(cls.custom_settings or {}),
            **{
                # "COOKIES_ENABLED": False,
                "DOWNLOAD_TIMEOUT": 200,
                # "CONCURRENT_REQUESTS": 2,
                "HTTPERROR_ALLOWED_CODES": [302, 400, 404, 500, 200, 202, 502, 429, 521],
                # "DOWNLOAD_DELAY": 5,
                # "DOWNLOADER_MIDDLEWARES": {
                #     "components.middlewares.downloadmiddlewares.public.jsl_middlewares.JslMiddleware": 543,
                #     **downloader_middlewares
                # }
            },
        }
        settings.setdict(new_settings or {}, priority="spider")

    def start_requests(self):
        for source, county, url in [
            ['宁波市宁海县人民政府', "宁海县", "https://www.ninghai.gov.cn/col/col1229114090/index.html?kong=zcwj"],
        ]:
            yield scrapy.Request(url, callback=self._parser_dataproxy_html,
                                 meta={"item": {'source': source, 'county': county}})

    def _parser_dataproxy_html(self, response):
        meta = response.meta
        ul = response.xpath('//*[@class="sonbox gfxwj" or @class="sonbox qtwj"]')
        
        urls = ul.re(r"""\[CDATA\[<a href="(.*?)"></a>\]\]></nextgroup>""")
        for next_url in urls:
            url_model = urllib.parse.urlparse(next_url)
            url = response.urljoin(response.url.split('/col/')[0] + url_model.path)
            params = {"startrecord": 1, "endrecord": self.page_size * 3, "perpage": self.page_size, }
            data = dict(urllib.parse.parse_qsl(url_model.query))
            if "webname" in data:
                data["webname"] = urllib.parse.unquote(data["webname"])
            data['col'] = data['sourceContentType'] = '1'
            data.pop('page')
            if response.url:
                headers = {"Referer": response.url}
            else:
                headers = {}
            if url[-1] != "?":
                url += "?"
            temp_url = url
            temp_url += urllib.parse.urlencode(params)
            meta.update({
                "params": params,
                "data": data,
                "url": url,
                "headers": headers,
            })
            yield self.FormRequest(
                temp_url,
                formdata=data,
                method="POST",
                headers=headers,
                callback=self.parse_list,
                meta=meta
            )

    def parse_list(self, response, **kwargs):
        prev_item = response.meta.get('item')
        meta = response.meta
        url = meta['url']
        for elem in response.xpath("//record"):
            item = Item()
            # url_select = elem.xpath("./text()").get()
            item['source_url'] = elem.xpath(".//a[contains(@href, 'htm')]/@href").get()
            if not item['source_url']:
                item['source_url'] = scrapy.Selector(text=elem.xpath("./text()").get()).xpath(".//a[contains(@href, 'htm')]/@href").get()
            if not item['source_url']:
                print('ERROR')
            item['source_url'] = response.urljoin(item['source_url'])
            # item['publish_date'] = elem['publishedTimeStr'].split(" ")[0]
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            print(response.url, item['source_url'])
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        total_page = int(response.xpath("string(//totalpage)").get())
        totalrecord = int(response.xpath("string(//totalrecord)").get())
        page = meta.get('page', 1)
        total_page = math.ceil(int(total_page) / 3)
        print(meta['data'], page, "total_page", total_page, totalrecord)
        if total_page and page < total_page:
            page += 1
            params = {
                "startrecord": ((page - 1) * self.page_size * 3) + 1,
                "endrecord": page * self.page_size * 3,
                "perpage": self.page_size,
            }
            meta['params'] = params
            meta['page'] = page
            temp_url = url
            temp_url += urllib.parse.urlencode(params)
            self.logger.info(f"{total_page} 开始爬取 第 {page} 页 params: {params}")
            yield self.FormRequest(
                temp_url,
                formdata=meta['data'],
                method="POST",
                meta=meta,
                headers=meta['headers'],
                callback=self.parse_list
            )

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").get() or response.xpath(
            "//*[@class='fbrq']/text()").get()
        if item['publish_date']:
            item['publish_date'] = item['publish_date'].split(" ")[0]
        item['content'] = response.xpath(""".""").get()
        # item['source'] = self.source
        item['province'] = self.province
        item['city'] = self.city
        # item['county'] = self.county
        item['park'] = self.park
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl zhejiang_ningbo_nh_policy -a get_next=0".split())
